<?php
declare (strict_types=1);

namespace app\api\controller;

use app\Request;
use DateInterval;
use think\captcha\facade\Captcha;
use app\common\JwtAuth;
use app\common\Log;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\response\Json;

class Auth
{
    public function __contruct()
    {
        $this->middleware->clear();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 生成图片验证码
     * @return void
     */
    public function captcha()
    {
        $jwt = new JwtAuth();
        // 用时间戳加微秒级随机数生成验证码key
        $captchaKey = $jwt->createToken(time() . '/' . uniqid());

        $captcha = Captcha::create();
//        $captchaKey =session('captcha');
        // 将验证码按照指定的key存储到session中
//        Session::set($captchaKey, $code);

        // 获取验证码图片的二进制数据
        $imageData = $captcha->getContent();
        // 图片二进制流转base64
        $base64Image = 'data:image/png;base64,' . base64_encode($imageData);
        return success(array(
            'captchaKey' =>
                $captchaKey,
            'captchaBase64' => $base64Image
        ));
    }

    /**
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login()
    {
        // 获取传入的参数
        $params = request()->post();
        $code = $params['captchaCode'];
        $mobile = $params['mobile'];
        $password = md5('cdfh_' . $params['password']);
        try {
            $captcha = new Captcha();
            if (!Captcha::check($code)) {
                throw  new Exception('验证错误',9004);
            }
            // 先查询管理员表是否存在数据
            $user = Db::name('user')->where([['mobile', '=', $mobile], ['password', '=', $password]])->find();
            if ($user != null) {
                if ($user['status'] != 1) {
                    return error([], 3003, '账号已被冻结无法使用，请联系管理员');
                }
                $jwt = new JwtAuth();
                // 生成登录token并且写入缓存  暂定缓存 时间为1天
                $token = $jwt->createToken($user['id'].'_mini');
                // 根据用户类型进行进行数据关联操作
                if ($user['type'] == 2) { // 如果是代理
                    $agentData = Db::name('agent')->where('account', '=', $user['id'])->find();
                    $user['identity_info'] = $agentData;
                } else if ($user['type'] == 3) {
                    $insData = Db::name('organ')->where('user_id', '=', $user['id'])->find();
                    $user['identity_info'] = $insData;
                } else {

                }
                // 将用户数据以缓存形式存储到token的key中
                Cache::set($token, $user, DateInterval::createFromDateString('100 day'));
                // 更新管理账号数据表信息
                $update = array(
                    'id' => $user['id'],
                    'token' => $token,
                    'last_time' => time()
                );
                // 日志表数据
                Log::write('用户登录考级平台', $user['id']);

                // 更新账号表数据
                Db::name('user')->save($update);
                $user['token'] = $token;
                $response = array(
                    'accessToken' => $token,
                    'tokenType' => 'Bearer',
                    'expires' => null,
                    'refreshToken' => null
                );
                return success($response);

            } else {
                return error([], 3003, '账号或者密码错误');

            }
        } catch (\Exception $e) {
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }

    /**
     * @param Request $request
     * @return Json
     */
    public function logout(Request $request): Json
    {
        $token = trim(str_replace("Bearer ", "", $request->header('Authorization')));
        $cache = Cache::get($token);
        Log::write('用户退出活动平台', $cache['id']);
        Cache::delete($token);
        return success();
    }

}
